package com.init.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;

public class JwtUtils {
    private static final String SECRET = "YOUR_SECRET"; // 秘钥
    private static final long EXPIRE_TIME = 86400000; // 令牌过期时间

    /**
     * 生成 token
     * @param accountId 用户id
     * @param username 用户名
     * @param role 角色id
     * @return
     */
    public static String createToken(Integer accountId, String username, String role) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        return JWT.create()
                .withClaim("accountId", accountId)
                .withClaim("username", username)
                .withClaim("role", role)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     *  校验token
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException exception) {
            return false;
        }
    }

    /**
     * 获取token用户id
     * @param token
     * @return
     */
    public static Integer getAccountId(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("accountId").asInt();
    }

    /**
     * 获取token用户名
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("username").asString();
    }

    /**
     *  获取token角色id
     * @param token
     * @return
     */
    public static String getRole(String token) {
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("role").asString();
    }
}
